<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize.js'
import { personClassify } from '@/api/user'
import { getUserId } from '@/utils/auth'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      data: [],
      datas: [],
      userId: -1
    }
  },
  watch: {
    $route: {
      handler() {
        if (this.$route.query.userId !== undefined) {
          this.userId = this.$route.query.userId
          this.personClassify()
        } else if (getUserId() !== undefined) {
          this.userId = getUserId()
          this.personClassify()
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.$route.query.userId !== undefined) {
      this.userId = this.$route.query.userId
      this.personClassify()
    } else if (getUserId() !== undefined) {
      this.userId = getUserId()
      this.personClassify()
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    personClassify() {
      personClassify({ userId: this.userId }).then(res => {
        this.data = res.data.data
        this.datas = res.data.datas
        this.$nextTick(() => {
          this.initChart()
        })
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: this.data
        },
        series: [
          {
            name: 'WEEKLY WRITE ARTICLES',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: this.datas,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
